package com.itheima.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
@Component
public class FileUploadUTils {
  @Autowired
  AliOssProperties aliOssProperties;
    public String uploadFile(MultipartFile image) throws IOException {
        //1. 获取用户上传文件的后缀
        String originalFilename = image.getOriginalFilename(); // fj.jpg  合同。pdf

        // 从文件名称中截取文件的后缀
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));


        //2. 生产唯一随机资源名称
        String fileName = UUID.randomUUID().toString() + fileType;


        //3. 调用MultipartFile  提供的api方法：transferTo 将用户上传的文件存储指定的服务器磁盘目录上
        //image.transferTo(new File("E:\\小陈\\Pictures\\Saved Pictures"+fileName +".jpg"));

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。

        // 3.1 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint(),aliOssProperties.getAccessId(), aliOssProperties.getAccsessKey());

        try {
            //3.2 上传文件
            ossClient.putObject(aliOssProperties.getBucketName(), fileName, image.getInputStream());
        } catch (OSSException oe) {
        } catch (ClientException ce) {
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //4. 返回oss的资源路径
        String path = "https://" + aliOssProperties.getBucketName() + "." + aliOssProperties.getEndpoint() + "/" + fileName;
        return path;
    }
}
